package com.yykj.user.center.server.service.impl.patient;

import com.alibaba.fastjson.JSON;
import com.yykj.common.util.LocalStringUtil;
import com.yykj.common.vo.PageData;
import com.yykj.user.center.server.dto.CommentDTO;
import com.yykj.user.center.server.dto.EvaluationDTO;
import com.yykj.user.center.server.form.EvaluationForm;
import com.yykj.user.center.server.model.ConsultationInfoOrder;
import com.yykj.user.center.server.model.Evaluation;
import com.yykj.user.center.server.model.Patient;
import com.yykj.user.center.server.repository.patient.ConsultationInfoRepository;
import com.yykj.user.center.server.repository.patient.EvaluationRepository;
import com.yykj.user.center.server.repository.patient.PatientRepository;
import com.yykj.user.center.server.service.patient.EvaluationService;
import com.yykj.user.center.server.service.patient.PaymentService;
import com.yykj.user.center.server.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenl
 * @version 1.0
 * @date 2021/10/30 22:13
 */
@Service
public class EvaluationServiceImpl implements EvaluationService {

    @Autowired
    private EvaluationRepository evaluationRepository;
    @Autowired
    private ConsultationInfoRepository consultationInfoRepository;
    @Autowired
    private PatientRepository patientRepository;
    @Autowired
    private PaymentService paymentService;


    @Override
    public Boolean evaluate(EvaluationForm evaluationForm) {
        String consultationId = evaluationForm.getConsultationId();
        ConsultationInfoOrder consultationInfoOrder = consultationInfoRepository.findById(consultationId).orElse(null);
        if(consultationInfoOrder!=null){
            Evaluation evaluation = new Evaluation();
            BeanUtils.copyProperties(evaluationForm,evaluation);
            evaluation.setPatientName(consultationInfoOrder.getPatientName());
            evaluation.setDoctorId(consultationInfoOrder.getDoctorId());
            evaluation.setConsultationId(consultationId);
            evaluation.setOrderNo(consultationInfoOrder.getOrderNo());
            evaluation.setOrderType(consultationInfoOrder.getOrderType());
            evaluation.setDeptName(consultationInfoOrder.getDeptName());
            evaluation.setDoctorName(consultationInfoOrder.getDoctorName());
            evaluation.setHospitalId(consultationInfoOrder.getHospitalId());
            evaluation.setId(LocalStringUtil.getUUID());
            evaluation.setState(true);
            evaluationRepository.save(evaluation);
            //医生给患者发送消息，提示评价发送成功
            Map dataMap = new HashMap();
            dataMap.put("type",1);
            dataMap.put("data","评价提交成功");
            paymentService.sendPayedMsg(consultationInfoOrder.getDoctorTencentAccountId(),consultationInfoOrder.getPatientTencentAccountId(), JSON.toJSONString(dataMap),2);
        }
        return true;
    }

    @Override
    public List<CommentDTO> showEvaluate(String doctorId) {
        List<Evaluation> evaluations = evaluationRepository.findByDoctorIdAndStateOrderByAddTimeDesc(doctorId,true);
        LocalDate currentDay = LocalDate.now();
        LocalDate yesterday = currentDay.minus(1, ChronoUnit.DAYS);
        List<CommentDTO> commentDTOS = new ArrayList<>();
        for(Evaluation evaluation:evaluations){
            LocalDateTime localDateTime = evaluation.getAddTime();
            LocalDate createDate = localDateTime.toLocalDate();
            CommentDTO commentDTO = new CommentDTO();
            commentDTO.setComment(evaluation.getComment());
            if(yesterday.isEqual(createDate)){
                String timeString = DateUtil.dateTime2TimeString(localDateTime);
                commentDTO.setDateTime("昨天 "+timeString);
            }else if(currentDay.equals(createDate)){
                String timeString = DateUtil.dateTime2TimeString(localDateTime);
                commentDTO.setDateTime(timeString);
            }else{
                String dateTimeString = DateUtil.dateTime2String(localDateTime);
                commentDTO.setDateTime(dateTimeString);
            }
            /*tring patientId = evaluation.getPatientId();
            Patient patient = patientRepository.findById(patientId).orElse(null);
            if(patient!=null){
                commentDTO.setName(StringUtils.isBlank(patient.getPatientName())? StringUtil.nameSplit(patient.getNickName()).get(0)+"**":StringUtil.nameSplit(patient.getPatientName()).get(0)+"**");
            }*/
            commentDTO.setName(evaluation.getPatientName());
            commentDTOS.add(commentDTO);
        }
        return commentDTOS;
    }

    @Override
    public PageData<EvaluationDTO> list(Integer current, Integer size, String startDate, String endDate, String patientName, String mobile, String orderNo, Integer orderType, String deptName, String doctorName, Integer hospitalId) {
        Pageable pageable = PageRequest.of(current, size, Sort.by(Sort.Order.desc("addTime")));
        Page<Evaluation> list = evaluationRepository.findAll(new Specification<Evaluation>() {
            @Override
            public Predicate toPredicate(Root<Evaluation> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(builder.equal(root.get("hospitalId"),hospitalId));
                if (org.apache.commons.lang3.StringUtils.isNotBlank(startDate) && org.apache.commons.lang3.StringUtils.isNotBlank(endDate)) {
                    LocalDate start = DateUtil.stringDate2Date(startDate);
                    LocalDate end = DateUtil.stringDate2Date(endDate);
                    predicateList.add(builder.between(root.get("addTime"), start, end));
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(patientName)) {
                    predicateList.add(builder.like(root.get("patientName"), patientName));
                }

                if (org.apache.commons.lang3.StringUtils.isNotBlank(mobile)) {
                    predicateList.add(builder.like(root.get("mobile"), mobile));
                }

                if (org.apache.commons.lang3.StringUtils.isNotBlank(orderNo)) {
                    predicateList.add(builder.like(root.get("orderNo"), orderNo));
                }

                if (orderType != null) {
                    predicateList.add(builder.equal(root.get("orderType"), orderType));
                }

                if (StringUtils.isNotBlank(deptName)) {
                    predicateList.add(builder.like(root.get("deptName"), deptName));
                }
                if (StringUtils.isNotBlank(doctorName)) {
                    predicateList.add(builder.equal(root.get("doctorName"), doctorName));
                }
                Predicate[] predicates = new Predicate[predicateList.size()];
                return query.where(predicateList.toArray(predicates)).getRestriction();
            }
        }, pageable);
        List<EvaluationDTO> evaluationDTOS = new ArrayList<>();
        for (Evaluation evaluation : list.getContent()) {
            EvaluationDTO evaluationDTO = new EvaluationDTO();
            BeanUtils.copyProperties(evaluation, evaluationDTO);
            String consultationId = evaluation.getConsultationId();
            ConsultationInfoOrder consultationInfoOrder = consultationInfoRepository.findById(consultationId).orElse(null);
            if(consultationInfoOrder!=null){
                String accountId = consultationInfoOrder.getPayAccountId();
                Patient patient = patientRepository.findById(accountId).orElse(null);
                if(patient!=null){
                    evaluationDTO.setAvatar(patient.getAvatar());
                }
            }
            evaluationDTOS.add(evaluationDTO);
        }
        PageData page = new PageData();
        page.setList(evaluationDTOS);
        page.setCurrentPage(current);
        page.setPageSize(size);
        page.setTotalCount(list.getTotalElements());
        return page;
    }

    @Override
    public EvaluationDTO info(String id) {
        Evaluation evaluation = evaluationRepository.findById(id).orElse(null);
        EvaluationDTO evaluationDTO = new EvaluationDTO();
        if(evaluation!=null){
            BeanUtils.copyProperties(evaluation,evaluationDTO);
        }
        return evaluationDTO;
    }
}
